<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图生图API客户端示例</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        input[type="text"], textarea, input[type="file"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
        textarea {
            height: 100px;
            resize: vertical;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin-top: 30px;
            padding: 20px;
            border-radius: 5px;
            background-color: #f8f9fa;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .image-container {
            text-align: center;
            margin: 20px 0;
        }
        .generated-image {
            max-width: 100%;
            max-height: 500px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .session-info {
            background-color: #e7f3ff;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .loading {
            text-align: center;
            padding: 20px;
        }
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 2s linear infinite;
            margin: 0 auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎨 图生图API客户端示例</h1>
        
        <div class="session-info" id="sessionInfo">
            <strong>会话状态:</strong> <span id="sessionStatus">未创建</span>
            <button onclick="createSession()">创建新会话</button>
        </div>

        <div class="form-group">
            <label for="prompt">文本提示:</label>
            <textarea id="prompt" placeholder="请输入您想要生成或编辑图片的描述...">生成一只可爱的小猫咪，坐在花园里</textarea>
        </div>

        <div class="form-group">
            <label for="imageFile">上传图片 (可选，用于图片编辑):</label>
            <input type="file" id="imageFile" accept="image/*" onchange="previewImage()">
        </div>

        <div class="image-container" id="previewContainer" style="display: none;">
            <h3>预览图片:</h3>
            <img id="previewImage" class="generated-image">
        </div>

        <div class="form-group">
            <button onclick="generateImage()" id="generateBtn">🎨 生成/编辑图片</button>
            <button onclick="clearResults()">🗑️ 清除结果</button>
        </div>

        <div id="loading" class="loading" style="display: none;">
            <div class="spinner"></div>
            <p>正在生成图片，请稍候...</p>
        </div>

        <div id="result" class="result" style="display: none;"></div>
    </div>

    <script>
        let currentSessionId = null;
        const API_BASE = 'http://localhost:5000/api/v1';

        // 创建会话
        async function createSession() {
            try {
                const response = await fetch(`${API_BASE}/session`, {
                    method: 'POST'
                });
                const data = await response.json();
                
                if (data.success) {
                    currentSessionId = data.data.session_id;
                    document.getElementById('sessionStatus').textContent = `已创建 (${currentSessionId.substring(0, 8)}...)`;
                    showResult('会话创建成功！', 'success');
                } else {
                    showResult('会话创建失败: ' + data.message, 'error');
                }
            } catch (error) {
                showResult('会话创建失败: ' + error.message, 'error');
            }
        }

        // 预览上传的图片
        function previewImage() {
            const file = document.getElementById('imageFile').files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('previewImage').src = e.target.result;
                    document.getElementById('previewContainer').style.display = 'block';
                };
                reader.readAsDataURL(file);
            } else {
                document.getElementById('previewContainer').style.display = 'none';
            }
        }

        // 生成图片
        async function generateImage() {
            const prompt = document.getElementById('prompt').value.trim();
            if (!prompt) {
                showResult('请输入文本提示', 'error');
                return;
            }

            const generateBtn = document.getElementById('generateBtn');
            generateBtn.disabled = true;
            document.getElementById('loading').style.display = 'block';
            document.getElementById('result').style.display = 'none';

            try {
                const formData = new FormData();
                formData.append('prompt', prompt);
                
                if (currentSessionId) {
                    formData.append('session_id', currentSessionId);
                }

                const imageFile = document.getElementById('imageFile').files[0];
                if (imageFile) {
                    formData.append('image', imageFile);
                }

                const response = await fetch(`${API_BASE}/generate`, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    currentSessionId = data.data.session_id;
                    document.getElementById('sessionStatus').textContent = `已创建 (${currentSessionId.substring(0, 8)}...)`;
                    
                    let resultHtml = '<h3>✅ 生成成功！</h3>';
                    
                    if (data.data.text) {
                        resultHtml += `<p><strong>AI响应:</strong> ${data.data.text}</p>`;
                    }
                    
                    if (data.data.image) {
                        resultHtml += `
                            <div class="image-container">
                                <h4>生成的图片:</h4>
                                <img src="${data.data.image}" class="generated-image" alt="生成的图片">
                                <br><br>
                                <button onclick="downloadImage('${data.data.image}')">📥 下载图片</button>
                            </div>
                        `;
                    }
                    
                    showResult(resultHtml, 'success');
                } else {
                    showResult('生成失败: ' + data.message, 'error');
                }
            } catch (error) {
                showResult('生成失败: ' + error.message, 'error');
            } finally {
                generateBtn.disabled = false;
                document.getElementById('loading').style.display = 'none';
            }
        }

        // 下载图片
        function downloadImage(base64Data) {
            const link = document.createElement('a');
            link.href = base64Data;
            link.download = `generated_image_${Date.now()}.png`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 显示结果
        function showResult(message, type) {
            const resultDiv = document.getElementById('result');
            resultDiv.innerHTML = message;
            resultDiv.className = `result ${type}`;
            resultDiv.style.display = 'block';
        }

        // 清除结果
        function clearResults() {
            document.getElementById('result').style.display = 'none';
            document.getElementById('previewContainer').style.display = 'none';
            document.getElementById('imageFile').value = '';
        }

        // 页面加载时自动创建会话
        window.onload = function() {
            createSession();
        };
    </script>
</body>
</html>
